package com.ws.shop.common;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Semaphore;

import com.ws.shop.entity.Auction;

public abstract class CacheSynLock<T> {

	 /**
	  * 
     * @Fields signMap : TODO(存储一个同步信号量，key表示同步的值)
     * 
     */
    private static  ConcurrentMap<Object, Semaphore> signMap = new ConcurrentHashMap<Object, Semaphore>();
    
    /** 
     * 
     * 要执行的方法
     * 
     */  
    public abstract void run();
    
    /**
     * 
     * 更新MAP
     * 
     */
    public abstract String getValue(T aid);
    
    public abstract Auction getAuctionByBid(T aid);
    
    public abstract Auction robotsbid(T aid);
    
    public String value(T value){
    	  Semaphore se = putMapAndGetSemaphore(value);   
          try {   
              se.acquire();   
          } catch (InterruptedException e) {   
              e.printStackTrace();   
          }   
          String v = getValue(value);
          releaseLockMap(value);   
          se.release();
          return v;
    }
    
    
    public Auction bidAuction(T value){
    	  Semaphore se = putMapAndGetSemaphore(value);   
          try {   
              se.acquire();   
          } catch (InterruptedException e) {   
              e.printStackTrace();   
          }   
          Auction auction = getAuctionByBid(value);
          releaseLockMap(value);   
          se.release();
          return auction;
    }
    
    public Auction robotbid(T value){
    	  Semaphore se = putMapAndGetSemaphore(value);   
          try {
              se.acquire();   
          } catch (InterruptedException e) {   
              e.printStackTrace();   
          }
          Auction auction = robotsbid(value);
          releaseLockMap(value);   
          se.release();
          return auction;
    }
    
    /**  
     * 开始执行操作  
     * @param value  
     */  
    public void startWork(T value) {   
        Semaphore se = putMapAndGetSemaphore(value);   
        try {   
            se.acquire();   
        } catch (InterruptedException e) {   
            e.printStackTrace();   
        }   
        run();   
        releaseLockMap(value);   
        se.release();   
    }
    /**  
     * 释放map  
     * @param   
     */  
    public void releaseLockMap(T a) {   
        Semaphore se = signMap.get(a);   
        if (se != null) {   
            signMap.remove(a);   
        }   
    }   
    /**  
     *   
     * @param 放入同步值，获取同步信号量  
     * @return  
     */  
    public Semaphore putMapAndGetSemaphore(T value) {   
        Semaphore se = signMap.get(value);   
        if (se == null) {   
            se = new Semaphore(1);   
            signMap.put(value, se);   
        }   
        return signMap.get(value);   
    }
    
}
